/*
 * flash.c
 *
 * Created: 17/01/2014 11:11:06
 *  Author: usuario
 */ 

#include "flash.h"

xSemaphoreHandle xSemaphore_flash;

void FLASH_setup ( void )
{
	extern uint32_t _etext;
	uint32_t ul_rc;
	
	//Check the flash doesn't override the program.
	configASSERT((void *) FLASH_ADDR> (void *) &_etext);
	
	ul_rc = flash_init(FLASH_ACCESS_MODE_128, 6);
	configASSERT(ul_rc == FLASH_RC_OK);

	ul_rc = flash_unlock(FLASH_ADDR, FLASH_LAST_ADDR, 0, 0);
	configASSERT(ul_rc == FLASH_RC_OK);
	
	xSemaphore_flash = xSemaphoreCreateMutex();
	configASSERT(xSemaphore_flash);
}


uint8_t flash_write_block (const void *__src, void *__dst, size_t __n)
{
	uint32_t ul_rc;
	
	if (((uint32_t) __dst + __n) < FLASH_SIZE)
	{
		xSemaphoreTake(xSemaphore_flash, portMAX_DELAY);
		ul_rc = flash_write((uint32_t) FLASH_ADDR + (uint32_t) __dst, __src ,	__n, 1);
		xSemaphoreGive(xSemaphore_flash);
		if (ul_rc == FLASH_RC_OK) return 1;
	}
	return 0;
}

uint8_t flash_read_block (void *__dst, const void *__src, size_t __n)
{
	if (((uint32_t) __src + __n) < FLASH_SIZE)
	{
		xSemaphoreTake(xSemaphore_flash, portMAX_DELAY);
		memcpy( __dst, (const void *) ((uint32_t) FLASH_ADDR + (uint32_t) __src), __n);
		xSemaphoreGive(xSemaphore_flash);
		return 1;
	}
	return 0;
}